//
//  ZFCustomControlView.m
//  ZFPlayer_Example
//
//  Created by 紫枫 on 2019/6/5.
//  Copyright © 2019 紫枫. All rights reserved.
//

#import "ZFCustomControlView.h"
#import "UIView+ZFFrame.h"
#import "ZFUtilities.h"
#import <ZFPlayer/ZFPlayerController.h>
#import <ZFPlayer/ZFPlayerConst.h>
#import "ZFSliderView.h"
#import "UIImageView+ZFCache.h"
#import "YBShareView.h"
#import "WuyouTangReportVC.h"
#import "TCVideoRecordViewController.h"
#import "addHotVideoVC.h"
#import "commentview.h"
#import "LandscapeShareView.h"

@interface ZFCustomControlView () <ZFSliderViewDelegate>
{
    
    BOOL _isDownLoading;
    MBProgressHUD *hud;
     NSURL *fullPathsss;

}
/// 底部工具栏
@property (nonatomic, strong) UIView *bottomToolView;
/// 顶部工具栏
@property (nonatomic, strong) UIView *topToolView;
/// 标题
@property (nonatomic, strong) UILabel *titleLabel;
/// 播放或暂停按钮
@property (nonatomic, strong) UIButton *playOrPauseBtn;
/// 播放的当前时间
@property (nonatomic, strong) UILabel *currentTimeLabel;
/// 滑杆
@property (nonatomic, strong) ZFSliderView *slider;
/// 视频总时间
@property (nonatomic, strong) UILabel *totalTimeLabel;
/// 全屏按钮
@property (nonatomic, strong) UIButton *fullScreenBtn;
//喜欢按钮
@property (nonatomic, strong) UIButton *likeBtn;
//评论按钮
@property (nonatomic, strong) UIButton *commentBtn;
@property (nonatomic, strong) commentview *commentView;

@property (nonatomic, strong) UIView *commentBackView;
@property (nonatomic, strong) LandscapeShareView *landShareView;
//评论按钮
@property (nonatomic, strong) UIButton *shareBtn;

@property (nonatomic, assign) BOOL isShow;

@property (nonatomic, assign) BOOL controlViewAppeared;

@property (nonatomic, strong) dispatch_block_t afterBlock;

@property (nonatomic, assign) NSTimeInterval sumTime;

/// 底部播放进度
@property (nonatomic, strong) ZFSliderView *bottomPgrogress;

/// 加载loading
@property (nonatomic, strong) ZFSpeedLoadingView *activity;

/// 封面图
@property (nonatomic, strong) UIImageView *coverImageView;

@end

@implementation ZFCustomControlView
@synthesize player = _player;

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // 添加子控件
        [self addSubview:self.topToolView];
        [self addSubview:self.bottomToolView];
        [self.topToolView addSubview:self.titleLabel];
        [self.bottomToolView addSubview:self.currentTimeLabel];
        [self.bottomToolView addSubview:self.slider];
        [self.bottomToolView addSubview:self.totalTimeLabel];
        [self.bottomToolView addSubview:self.playOrPauseBtn];
        [self.bottomToolView addSubview:self.likeBtn];
        [self.bottomToolView addSubview:self.commentBtn];
        [self.bottomToolView addSubview:self.shareBtn];

//        [self.bottomToolView addSubview:self.fullScreenBtn];
//        [self addSubview:self.bottomPgrogress];
        [self addSubview:self.fullScreenBtn];
        [self addSubview:self.activity];
        
        self.autoFadeTimeInterval = 0.2;
        self.autoHiddenTimeInterval = 2.5;

        // 设置子控件的响应事件
        [self makeSubViewsAction];
        
        [self resetControlView];
        self.clipsToBounds = YES;
    }
    return self;
}

- (void)makeSubViewsAction {
    [self.playOrPauseBtn addTarget:self action:@selector(playPauseButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.fullScreenBtn addTarget:self action:@selector(fullScreenButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - ZFSliderViewDelegate

- (void)sliderTouchBegan:(float)value {
    self.slider.isdragging = YES;
}

- (void)sliderTouchEnded:(float)value {
    if (self.player.totalTime > 0) {
        @zf_weakify(self)
        [self.player seekToTime:self.player.totalTime*value completionHandler:^(BOOL finished) {
            @zf_strongify(self)
            if (finished) {
                self.slider.isdragging = NO;
            }
        }];
    } else {
        self.slider.isdragging = NO;
    }
}

- (void)sliderValueChanged:(float)value {
    if (self.player.totalTime == 0) {
        self.slider.value = 0;
        return;
    }
    self.slider.isdragging = YES;
    NSString *currentTimeString = [ZFUtilities convertTimeSecond:self.player.totalTime*value];
    self.currentTimeLabel.text = currentTimeString;
}

- (void)sliderTapped:(float)value {
    if (self.player.totalTime > 0) {
        self.slider.isdragging = YES;
        @zf_weakify(self)
        [self.player seekToTime:self.player.totalTime*value completionHandler:^(BOOL finished) {
            @zf_strongify(self)
            if (finished) {
                self.slider.isdragging = NO;
                [self.player.currentPlayerManager play];
            }
        }];
    } else {
        self.slider.isdragging = NO;
        self.slider.value = 0;
    }
}

#pragma mark - action

- (void)playPauseButtonClickAction:(UIButton *)sender {
    [self playOrPause];
}

- (void)fullScreenButtonClickAction:(UIButton *)sender {
    [self.player enterFullScreen:!self.player.isFullScreen animated:YES];
    if(_commentView){
        [_commentView removeFromSuperview];
        _commentView = nil;
    }
    if(self.bottomEvent){
        self.bottomEvent(@"关闭评论");
    }
}

/// 根据当前播放状态取反
- (void)playOrPause {
    self.playOrPauseBtn.selected = !self.playOrPauseBtn.isSelected;
    self.playOrPauseBtn.isSelected? [self.player.currentPlayerManager play]: [self.player.currentPlayerManager pause];
}

- (void)playBtnSelectedState:(BOOL)selected {
    self.playOrPauseBtn.selected = selected;
}

#pragma mark - 添加子控件约束

- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGFloat min_x = 0;
    CGFloat min_y = 0;
    CGFloat min_w = 0;
    CGFloat min_h = 0;
    CGFloat min_view_w = self.bounds.size.width;
    CGFloat min_view_h = self.bounds.size.height;
    CGFloat min_margin = 9;
    
    self.coverImageView.frame = self.bounds;
    
    min_w = 80;
    min_h = 80;
    self.activity.frame = CGRectMake(min_x, min_y, min_w, min_h);
    self.activity.zf_centerX = self.zf_centerX;
    self.activity.zf_centerY = self.zf_centerY + 10;
    
    min_x = 0;
    min_y = 0;
    min_w = min_view_w;
    min_h = (iPhoneX && self.player.isFullScreen) ? 80 : 40;
    self.topToolView.frame = CGRectMake(min_x, min_y, min_w, min_h);
    
    min_x = self.player.isFullScreen ? 40: 15;
    min_y = 0;
    min_w = min_view_w - min_x - 15;
    min_h = 30;
    self.titleLabel.frame = CGRectMake(min_x, min_y, min_w, min_h);
    self.titleLabel.zf_centerY = self.topToolView.zf_centerY;

    min_h =100;// (iPhoneX && self.player.isFullScreen) ? 100 : 40;
    min_x = 0;
    min_y = min_view_h - min_h ;
    min_w = min_view_w;
    self.bottomToolView.frame = CGRectMake(min_x, min_y, min_w, min_h);
    
    
    
//    min_w = 28;
//    min_h = min_w;
//    min_x = self.bottomToolView.zf_width - min_w - ((iPhoneX && self.player.isFullScreen) ? 44: min_margin);
//    min_y = 0;
    min_x = 10;
    min_y=  10;
    min_h = 80;
    min_w = 80;

    self.fullScreenBtn.frame = CGRectMake(min_x, min_y, min_w, min_h);
//    self.fullScreenBtn.zf_centerY = self.currentTimeLabel.zf_centerY;
    
    
    min_x =0;
    min_y = 0;
    min_w =min_view_w;// self.totalTimeLabel.zf_left - min_x - 4;
    min_h = 30;
    self.slider.frame = CGRectMake(min_x, min_y, min_w, min_h);
//    self.slider.zf_centerY = self.currentTimeLabel.zf_centerY;
    
    
    min_x = 20;
    min_y = self.slider.bottom-10;
    min_w = 44;
    min_h = min_w;
    self.playOrPauseBtn.frame = CGRectMake(min_x, min_y, min_w, min_h);
//    self.playOrPauseBtn.center = self.center;

    min_x =self.playOrPauseBtn.right;// (iPhoneX && self.player.isFullScreen) ? 60: 35;
    min_w = 50;
    min_h = 28;
    min_y = self.slider.bottom;//(self.bottomToolView.zf_height - min_h)/2;
    self.currentTimeLabel.frame = CGRectMake(min_x, min_y, min_w, min_h);

    min_w = 62;
    min_h = 28;
    min_x = self.fullScreenBtn.zf_left - min_w - 4;
    min_y = self.slider.bottom;
    self.totalTimeLabel.frame = CGRectMake(self.currentTimeLabel.right, min_y, min_w, min_h);
    self.totalTimeLabel.zf_centerY = self.currentTimeLabel.zf_centerY;

    
    min_x = 0;
    min_y = min_view_h - 5;
    min_w = min_view_w;
    min_h = 2;
    self.bottomPgrogress.frame = CGRectMake(min_x, min_y, min_w, min_h);
    
    
    min_x = self.bottomToolView.width-110;
    min_y = self.slider.bottom-20;
    min_w = 70;
    min_h = 70;

    self.shareBtn.frame = CGRectMake(min_x, min_y, min_w, min_h);
    
    min_x = self.shareBtn.left-110;
    min_y = self.slider.bottom-20;
    min_w = 70;
    min_h = 70;

    self.commentBtn.frame = CGRectMake(min_x, min_y, min_w, min_h);

    min_x = self.commentBtn.left-110;
    min_y = self.slider.bottom-20;
    min_w = 70;
    min_h = 70;

    self.likeBtn.frame = CGRectMake(min_x, min_y, min_w, min_h);

//    self.topToolView.zf_y = 0;
//    self.bottomToolView.zf_y = self.zf_height - self.bottomToolView.zf_height;
//    self.playOrPauseBtn.alpha = 1;

//    if (!self.isShow) {
//        self.topToolView.zf_y = -self.topToolView.zf_height;
//        self.bottomToolView.zf_y = self.zf_height;
//        self.playOrPauseBtn.alpha = 0;
//    } else {
//        self.topToolView.zf_y = 0;
//        self.bottomToolView.zf_y = self.zf_height - self.bottomToolView.zf_height;
//        self.playOrPauseBtn.alpha = 1;
//    }
}

#pragma mark - private

/** 重置ControlView */
- (void)resetControlView {
    self.bottomToolView.alpha        = 1;
    self.slider.value                = 0;
    self.slider.bufferValue          = 0;
    self.currentTimeLabel.text       = @"00:00";
    self.totalTimeLabel.text         = @"/00:00";
//    self.backgroundColor             = [UIColor clearColor];

    self.playOrPauseBtn.selected     = YES;
    self.titleLabel.text             = @"";
}

- (void)showControlView {
//    self.topToolView.alpha           = 1;
//    self.bottomToolView.alpha        = 1;
//    self.isShow                      = YES;
//    self.topToolView.zf_y            = 0;
//    self.bottomToolView.zf_y         = self.zf_height - self.bottomToolView.zf_height;
//    self.playOrPauseBtn.alpha        = 1;
//    self.player.statusBarHidden      = NO;
}

- (void)hideControlView {
//    self.isShow                      = NO;
//    self.topToolView.zf_y            = -self.topToolView.zf_height;
//    self.bottomToolView.zf_y         = self.zf_height;
//    self.player.statusBarHidden      = NO;
//    self.playOrPauseBtn.alpha        = 0;
//    self.topToolView.alpha           = 0;
//    self.bottomToolView.alpha        = 0;
}

- (void)autoFadeOutControlView {
//    self.controlViewAppeared = YES;
//    [self cancelAutoFadeOutControlView];
//    @zf_weakify(self)
//    self.afterBlock = dispatch_block_create(0, ^{
//        @zf_strongify(self)
////        [self hideControlViewWithAnimated:YES];
//    });
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.autoHiddenTimeInterval * NSEC_PER_SEC)), dispatch_get_main_queue(),self.afterBlock);
}

/// 取消延时隐藏controlView的方法
- (void)cancelAutoFadeOutControlView {
    if (self.afterBlock) {
        dispatch_block_cancel(self.afterBlock);
        self.afterBlock = nil;
    }
}

/// 隐藏控制层
- (void)hideControlViewWithAnimated:(BOOL)animated {
//    self.controlViewAppeared = NO;
//    [UIView animateWithDuration:animated ? self.autoFadeTimeInterval : 0 animations:^{
//        [self hideControlView];
//    } completion:^(BOOL finished) {
//        self.bottomPgrogress.hidden = NO;
//    }];
}

/// 显示控制层
- (void)showControlViewWithAnimated:(BOOL)animated {
//    self.controlViewAppeared = YES;
//    [self autoFadeOutControlView];
//    [UIView animateWithDuration:animated ? self.autoFadeTimeInterval : 0 animations:^{
//        [self showControlView];
//    } completion:^(BOOL finished) {
//        self.bottomPgrogress.hidden = YES;
//    }];
}


//- (BOOL)shouldResponseGestureWithPoint:(CGPoint)point withGestureType:(ZFPlayerGestureType)type touch:(nonnull UITouch *)touch {
//    CGRect sliderRect = [self.bottomToolView convertRect:self.slider.frame toView:self];
//    if (CGRectContainsPoint(sliderRect, point)) {
//        return NO;
//    }
//    return YES;
//}

/**
 设置标题、封面、全屏模式
 
 @param title 视频的标题
 @param coverUrl 视频的封面，占位图默认是灰色的
 @param fullScreenMode 全屏模式
 */
- (void)showTitle:(NSString *)title coverURLString:(NSString *)coverUrl fullScreenMode:(ZFFullScreenMode)fullScreenMode {
    UIImage *placeholder = [ZFUtilities imageWithColor:[UIColor colorWithRed:220/255.0 green:220/255.0 blue:220/255.0 alpha:1] size:self.coverImageView.bounds.size];
    [self resetControlView];
    [self layoutIfNeeded];
    [self setNeedsDisplay];
    self.titleLabel.text = title;
    self.player.orientationObserver.fullScreenMode = fullScreenMode;
}

/// 调节播放进度slider和当前时间更新
- (void)sliderValueChanged:(CGFloat)value currentTimeString:(NSString *)timeString {
    self.slider.value = value;
    self.currentTimeLabel.text = timeString;
    self.slider.isdragging = YES;
    [UIView animateWithDuration:0.3 animations:^{
        self.slider.sliderBtn.transform = CGAffineTransformMakeScale(1.2, 1.2);
    }];
}

/// 滑杆结束滑动
- (void)sliderChangeEnded {
    self.slider.isdragging = NO;
    [UIView animateWithDuration:0.3 animations:^{
        self.slider.sliderBtn.transform = CGAffineTransformIdentity;
    }];
}

#pragma mark - ZFPlayerControlViewDelegate

/// 手势筛选，返回NO不响应该手势
- (BOOL)gestureTriggerCondition:(ZFPlayerGestureControl *)gestureControl gestureType:(ZFPlayerGestureType)gestureType gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer touch:(nonnull UITouch *)touch {
//    CGPoint point = [touch locationInView:self];
    if (self.player.isSmallFloatViewShow && !self.player.isFullScreen && gestureType != ZFPlayerGestureTypeSingleTap) {
        return NO;
    }
    if ([touch.view isDescendantOfView:_landShareView]||[touch.view isDescendantOfView:_commentView]) {
        return NO;
    }
    return YES;
//    return [self shouldResponseGestureWithPoint:point withGestureType:gestureType touch:touch];
}

/// 单击手势事件
- (void)gestureSingleTapped:(ZFPlayerGestureControl *)gestureControl {
    if (!self.player) return;
    if (self.player.isSmallFloatViewShow && !self.player.isFullScreen) {
//        [self.player enterFullScreen:YES animated:YES];
    } else {
        
//        if(_landShareView)
//        {
//            [_landShareView removeFromSuperview];
//            _landShareView = nil;
//        }

//        if (self.controlViewAppeared) {
//            [self hideControlViewWithAnimated:YES];
//        } else {
            /// 显示之前先把控制层复位，先隐藏后显示
//            [self hideControlViewWithAnimated:NO];
//            [self showControlViewWithAnimated:YES];
//        self.topToolView.zf_y = 0;
//        self.bottomToolView.zf_y = self.zf_height - self.bottomToolView.zf_height;
//        self.playOrPauseBtn.alpha = 1;

            if(_landShareView)
            {
                [_landShareView removeFromSuperview];
                _landShareView = nil;
            }
//        }
    }
}
//- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
//    NSLog(@"s0000000000:%@",NSStringFromClass([touch.view class]));
//    if ([touch.view isDescendantOfView:_landShareView]) {
//        return NO;
//    }
//    return YES;
//}

/// 双击手势事件
- (void)gestureDoubleTapped:(ZFPlayerGestureControl *)gestureControl {
    [self playOrPause];
}

/// 捏合手势事件，这里改变了视频的填充模式
- (void)gesturePinched:(ZFPlayerGestureControl *)gestureControl scale:(float)scale {
    if (scale > 1) {
        self.player.currentPlayerManager.scalingMode = ZFPlayerScalingModeAspectFill;
    } else {
        self.player.currentPlayerManager.scalingMode = ZFPlayerScalingModeAspectFit;
    }
}

/// 准备播放
- (void)videoPlayer:(ZFPlayerController *)videoPlayer prepareToPlay:(NSURL *)assetURL {
//    [self hideControlViewWithAnimated:NO];
}

/// 播放状态改变
- (void)videoPlayer:(ZFPlayerController *)videoPlayer playStateChanged:(ZFPlayerPlaybackState)state {
    if (state == ZFPlayerPlayStatePlaying) {
        [self playBtnSelectedState:YES];
        /// 开始播放时候判断是否显示loading
        if (videoPlayer.currentPlayerManager.loadState == ZFPlayerLoadStateStalled) {
            [self.activity startAnimating];
        } else if ((videoPlayer.currentPlayerManager.loadState == ZFPlayerLoadStateStalled || videoPlayer.currentPlayerManager.loadState == ZFPlayerLoadStatePrepare)) {
            [self.activity startAnimating];
        }
    } else if (state == ZFPlayerPlayStatePaused) {
        [self playBtnSelectedState:NO];
        /// 暂停的时候隐藏loading
        [self.activity stopAnimating];
    } else if (state == ZFPlayerPlayStatePlayFailed) {
        [self.activity stopAnimating];
    }
}

/// 加载状态改变
- (void)videoPlayer:(ZFPlayerController *)videoPlayer loadStateChanged:(ZFPlayerLoadState)state {
    if (state == ZFPlayerLoadStatePrepare) {
        self.coverImageView.hidden = NO;
    } else if (state == ZFPlayerLoadStatePlaythroughOK || state == ZFPlayerLoadStatePlayable) {
        self.coverImageView.hidden = YES;
        self.player.currentPlayerManager.view.backgroundColor = [UIColor blackColor];
    }
    if (state == ZFPlayerLoadStateStalled && videoPlayer.currentPlayerManager.isPlaying) {
        [self.activity startAnimating];
    } else if ((state == ZFPlayerLoadStateStalled || state == ZFPlayerLoadStatePrepare) && videoPlayer.currentPlayerManager.isPlaying) {
        [self.activity startAnimating];
    } else {
        [self.activity stopAnimating];
    }
}

/// 播放进度改变回调
- (void)videoPlayer:(ZFPlayerController *)videoPlayer currentTime:(NSTimeInterval)currentTime totalTime:(NSTimeInterval)totalTime {
    if (!self.slider.isdragging) {
        NSString *currentTimeString = [ZFUtilities convertTimeSecond:currentTime];
        self.currentTimeLabel.text = currentTimeString;
        NSString *totalTimeString = [ZFUtilities convertTimeSecond:totalTime];
        self.totalTimeLabel.text =[NSString stringWithFormat:@"/ %@",totalTimeString];
        self.slider.value = videoPlayer.progress;
    }
    self.bottomPgrogress.value = videoPlayer.progress;
}

/// 缓冲改变回调
- (void)videoPlayer:(ZFPlayerController *)videoPlayer bufferTime:(NSTimeInterval)bufferTime {
    self.slider.bufferValue = videoPlayer.bufferProgress;
    self.bottomPgrogress.bufferValue = videoPlayer.bufferProgress;
}

- (void)videoPlayer:(ZFPlayerController *)videoPlayer presentationSizeChanged:(CGSize)size {
    
}

/// 视频view即将旋转
- (void)videoPlayer:(ZFPlayerController *)videoPlayer orientationWillChange:(ZFOrientationObserver *)observer {
    if (videoPlayer.isSmallFloatViewShow) {
        if (observer.isFullScreen) {
            self.controlViewAppeared = NO;
            [self cancelAutoFadeOutControlView];
        }
    }
//    if (self.controlViewAppeared) {
//        [self showControlViewWithAnimated:NO];
//    } else {
//        [self hideControlViewWithAnimated:NO];
//    }
}

/// 视频view已经旋转
- (void)videoPlayer:(ZFPlayerController *)videoPlayer orientationDidChanged:(ZFOrientationObserver *)observer {
//    if (self.controlViewAppeared) {
//        [self showControlViewWithAnimated:NO];
//    } else {
//        [self hideControlViewWithAnimated:NO];
//    }
//    [self layoutIfNeeded];
//    [self setNeedsDisplay];
}

/// 锁定旋转方向
- (void)lockedVideoPlayer:(ZFPlayerController *)videoPlayer lockedScreen:(BOOL)locked {
    [self showControlViewWithAnimated:YES];
}

#pragma mark - setter

- (void)setPlayer:(ZFPlayerController *)player {
    _player = player;
}

#pragma mark - getter

- (UIView *)topToolView {
    if (!_topToolView) {
        _topToolView = [[UIView alloc] init];
        UIImage *image = ZFPlayer_Image(@"ZFPlayer_top_shadow");
        _topToolView.layer.contents = (id)image.CGImage;
    }
    return _topToolView;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.textColor = [UIColor whiteColor];
        _titleLabel.font = [UIFont systemFontOfSize:15.0];
    }
    return _titleLabel;
}

- (UIView *)bottomToolView {
    if (!_bottomToolView) {
        _bottomToolView = [[UIView alloc] init];
        UIImage *image = ZFPlayer_Image(@"ZFPlayer_bottom_shadow");
        _bottomToolView.layer.contents = (id)image.CGImage;
    }
    return _bottomToolView;
}

- (UIButton *)playOrPauseBtn {
    if (!_playOrPauseBtn) {
        _playOrPauseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_playOrPauseBtn setImage:ZFPlayer_Image(@"new_allPlay_44x44_") forState:UIControlStateNormal];
        [_playOrPauseBtn setImage:ZFPlayer_Image(@"new_allPause_44x44_") forState:UIControlStateSelected];
    }
    return _playOrPauseBtn;
}
- (UIButton *)likeBtn {
    if(!_likeBtn){
        _likeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_likeBtn setImage:[UIImage imageNamed:@"home_zan"] forState:0];
        _likeBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [_likeBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0 )];
        [_likeBtn setTitle:@"0" forState:0];
        [_likeBtn addTarget:self action:@selector(clickLikeBtn) forControlEvents:UIControlEventTouchUpInside];

    }
    return _likeBtn;
}
-(UIButton *)shareBtn{
    if(!_shareBtn){
        _shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_shareBtn setImage:[UIImage imageNamed:@"home_share"] forState:0];
        _shareBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [_shareBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0 )];
        [_shareBtn setTitle:@"0" forState:0];
        [_shareBtn addTarget:self action:@selector(clickEnjoyBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _shareBtn;

}
-(UIButton *)commentBtn{
    if(!_commentBtn){
        _commentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_commentBtn setImage:[UIImage imageNamed:@"home_comment"] forState:0];
        _commentBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [_commentBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0 )];
        [_commentBtn setTitle:@"0" forState:0];
        [_commentBtn addTarget:self action:@selector(clickCommentBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _commentBtn;

}

- (UILabel *)currentTimeLabel {
    if (!_currentTimeLabel) {
        _currentTimeLabel = [[UILabel alloc] init];
        _currentTimeLabel.textColor = [UIColor whiteColor];
        _currentTimeLabel.font = [UIFont systemFontOfSize:14.0f];
        _currentTimeLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _currentTimeLabel;
}

- (ZFSliderView *)slider {
    if (!_slider) {
        _slider = [[ZFSliderView alloc] init];
        _slider.delegate = self;
        _slider.maximumTrackTintColor = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:0.8];
        _slider.bufferTrackTintColor  = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.5];
        _slider.minimumTrackTintColor = [UIColor whiteColor];
        [_slider setThumbImage:ZFPlayer_Image(@"ZFPlayer_slider") forState:UIControlStateNormal];
        _slider.sliderHeight = 2;
    }
    return _slider;
}

- (UILabel *)totalTimeLabel {
    if (!_totalTimeLabel) {
        _totalTimeLabel = [[UILabel alloc] init];
        _totalTimeLabel.textColor = [UIColor whiteColor];
        _totalTimeLabel.font = [UIFont systemFontOfSize:14.0f];
        _totalTimeLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _totalTimeLabel;
}

- (UIButton *)fullScreenBtn {
    if (!_fullScreenBtn) {
        _fullScreenBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_fullScreenBtn setImage:[UIImage imageNamed:@"full_返回"] forState:UIControlStateNormal];
    }
    return _fullScreenBtn;
}

- (UIImageView *)coverImageView {
    if (!_coverImageView) {
        _coverImageView = [[UIImageView alloc] init];
        _coverImageView.userInteractionEnabled = YES;
    }
    return _coverImageView;
}

- (ZFSliderView *)bottomPgrogress {
    if (!_bottomPgrogress) {
        _bottomPgrogress = [[ZFSliderView alloc] init];
        _bottomPgrogress.maximumTrackTintColor = [UIColor clearColor];
        _bottomPgrogress.minimumTrackTintColor = [UIColor whiteColor];
        _bottomPgrogress.bufferTrackTintColor  = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.5];
        _bottomPgrogress.sliderHeight = 1;
        _bottomPgrogress.isHideSliderBlock = NO;
    }
    return _bottomPgrogress;
}
-(void)clickLikeBtn{
    NSLog(@"like:%@",_playDoc);
    if ([[Config getOwnID] intValue] <= 0) {
        [self.player enterFullScreen:!self.player.isFullScreen animated:YES];
        [PublicObj warnLogin];
        return;
    }
    if([[_playDoc valueForKey:@"uid"] isEqual:[Config getOwnID]]){
        [MBProgressHUD showError:@"不能给自己点赞" toView:self];
        return;
    }
    _likeBtn.userInteractionEnabled = NO;
    YBWeakSelf;
    [WYNetworking postWithUrl:@"Video.addLike" Dic:@{@"videoid":minstr([_playDoc valueForKey:@"id"])} Suc:^(int code, id info, NSString *msg) {
        //[MBProgressHUD hideHUD];
        _likeBtn.userInteractionEnabled = YES;
        if(code == 0) {
            
            NSDictionary *infoDic = [info firstObject];
            NSString *isLike = minstr([infoDic valueForKey:@"islike"]);
            NSString *likes  = minstr([infoDic valueForKey:@"likes"]);
            NSDictionary *newDic = @{@"islike":isLike,@"likes":likes};
            [weakSelf updateDataDic:newDic];
            [_likeBtn setTitle:likes forState:0];
            [weakSelf likeAnimationShowIsLike:isLike];
        }else{
            [MBProgressHUD showPop:msg];
        }
    } Fail:^(id fail) {
        //[MBProgressHUD hideHUD];
        _likeBtn.userInteractionEnabled = YES;
    }];

}
///点赞、评论、关注后这里也更新一下
-(void)updateDataDic:(NSDictionary *)dic {
    NSMutableDictionary *m_dic = [NSMutableDictionary dictionaryWithDictionary:_playDoc];
    [m_dic addEntriesFromDictionary:dic];
    _playDoc = [NSDictionary dictionaryWithDictionary:m_dic];
    
//    if (![PublicObj checkNull:_fromWhere]) {
        [[NSUserDefaults standardUserDefaults]setObject:_playDoc forKey:@"yb_update_video_on_other"];
//    }
}

//点赞-取消赞动画
-(void)likeAnimationShowIsLike:(NSString *)isLike {
    
    NSMutableArray *m_sel_arr = [NSMutableArray array];
    NSString *endImgName = @"";
    if ([isLike isEqual:@"1"]) {
        for (int i=1; i<=12; i++) {
            UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:@"icon_video_zan_%02d",i]];
            [m_sel_arr addObject:img];
        }
        endImgName = @"icon_video_zan_12";
    }else{
        for (int i=1; i<=6; i++) {
            UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:@"icon_video_zan_cancel_%02d",i]];
            [m_sel_arr addObject:img];
        }
        endImgName = @"icon_video_zan_01";
    }
    CGFloat showTime = 0.05*m_sel_arr.count;
    _likeBtn.imageView.animationImages = m_sel_arr;
    _likeBtn.imageView.animationDuration = showTime;
    _likeBtn.imageView.animationRepeatCount = 1;
    [_likeBtn.imageView startAnimating];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((showTime-0.06) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [_likeBtn.imageView stopAnimating];
        [_likeBtn setImage:[UIImage imageNamed:endImgName] forState:0];
    });
    
}

-(void)setPlayDoc:(NSDictionary *)playDoc
{
    NSLog(@"------cotrolview ==:%@",playDoc);
    _playDoc = playDoc;
    [self.likeBtn setTitle:minstr([playDoc valueForKey:@"likes"]) forState:0];
    NSString *isLike = minstr([playDoc valueForKey:@"islike"]);
    if ([isLike isEqual:@"1"]) {
        [_likeBtn setImage:[UIImage imageNamed:@"home_zan_sel"] forState:0];
    }else {
        [_likeBtn setImage:[UIImage imageNamed:@"home_zan"] forState:0];
    }

    [self.commentBtn setTitle:minstr([playDoc valueForKey:@"comments"]) forState:0];
    [self.shareBtn setTitle:minstr([playDoc valueForKey:@"shares"]) forState:0];
}

#pragma mark - 分享
-(void)clickEnjoyBtn {
    //NSLog(@"enjoy:%@",_dataDic);

    YBWeakSelf;
    [MBProgressHUD showMessage:@""];
    [WYNetworking postWithUrl:@"Video.checkPayVideoIsShare" Dic:@{@"videoid":minstr([self.playDoc valueForKey:@"id"])} Suc:^(int code, id info, NSString *msg) {
        [MBProgressHUD hideHUD];
        if (code == 0) {
            if ([info isKindOfClass:[NSArray class]]) {
                [weakSelf shareLimit:[info firstObject]];
            }else {
                [weakSelf shareLimit:info];
            }
        }else {
            [MBProgressHUD showError:msg];
        }
    } Fail:^(id fail) {
        [MBProgressHUD hideHUD];
    }];
}
-(void)shareLimit:(NSDictionary *)infoDic {
    YBWeakSelf;
    CGFloat min_view_w = self.bounds.size.width;
    CGFloat min_view_h = self.bounds.size.height;

    _landShareView = [[LandscapeShareView alloc]initWithFrame: CGRectMake(min_view_w-min_view_w *0.4,0, min_view_w *0.4, min_view_h)parameter:_playDoc andlimitDic:infoDic];
    
    _landShareView.shareEvent = ^(int codeEvent, NSString *nums) {
        if (codeEvent == 2){
            //举报
            if ([[Config getOwnID] intValue] <= 0) {
                [self.player enterFullScreen:!self.player.isFullScreen animated:YES];

                [PublicObj warnLogin];
                return;
            }
            [self.player enterFullScreen:!self.player.isFullScreen animated:YES];

            WuyouTangReportVC *jubao = [[WuyouTangReportVC alloc]init];
            jubao.dongtaiId =  minstr([weakSelf.playDoc valueForKey:@"id"]);;
            jubao.fromWhere = @"LookVideo";
            [[YBBaseAppDelegate sharedAppDelegate]pushViewController:jubao animated:YES];
        }else if (codeEvent == 4){
            //合拍
            if ([[Config getOwnID] intValue] <= 0) {
                [self.player enterFullScreen:!self.player.isFullScreen animated:YES];
                [PublicObj warnLogin];
                return;
            }
            if (self.player.totalTime < 5) {
                [MBProgressHUD showPop:YZMsg(@"该视频时长太短,无法合拍")];
                [[NSFileManager defaultManager] removeItemAtPath:nums error:nil];
                return;
            }
            if ([YBYoungManager shareInstance].youngSwitch == 1) {
                [MBProgressHUD showError:YZMsg(@"青少年模式下不支持该功能")];
                return;
            }
            [self.player enterFullScreen:!self.player.isFullScreen animated:YES];

            TCVideoRecordViewController *recorddVC = [[TCVideoRecordViewController alloc]init];
            recorddVC.mp4Path = nums;
            recorddVC.recordType = RecordType_Chorus;
            [[YBBaseAppDelegate sharedAppDelegate]pushViewController:recorddVC animated:YES];
        }else if (codeEvent == 5){
            //上热门
            if ([[Config getOwnID] intValue] <= 0) {
                [self.player enterFullScreen:!self.player.isFullScreen animated:YES];

                [PublicObj warnLogin];
                return;
            }
            if ([YBYoungManager shareInstance].youngSwitch == 1) {
                [MBProgressHUD showError:YZMsg(@"青少年模式下不支持该功能")];
                return;
            }
            [self.player enterFullScreen:!self.player.isFullScreen animated:YES];

            addHotVideoVC *hot = [[addHotVideoVC alloc]init];
            hot.videoInfo = self.playDoc;
            [[YBBaseAppDelegate sharedAppDelegate]pushViewController:hot animated:YES];
            
        }else if (codeEvent == 7){
            // 收藏
            if ([[Config getOwnID] intValue] <= 0) {
                [self.player enterFullScreen:!self.player.isFullScreen animated:YES];

                [PublicObj warnLogin];
                return;
            }
            [self.player enterFullScreen:!self.player.isFullScreen animated:YES];

            [weakSelf clickVideoCollectionAni:NO];

        }else if (codeEvent == 8){
            if (![minstr([infoDic valueForKey:@"limit_status"]) isEqual:@"1"]) {
                [MBProgressHUD showError:YZMsg(@"该视频不能复制链接")];
                return;
            }
            UIPasteboard *paste = [UIPasteboard generalPasteboard];
            if (![PublicObj checkNull:[_playDoc valueForKey:@"href"]]) {
                NSString *href = [NSString stringWithFormat:@"%@",[_playDoc valueForKey:@"href_w"]];
                if (href.length <= 0) {
                    [MBProgressHUD showError:YZMsg(@"该视频暂不支持复制链接")];
                    return;
                }
                [self.player enterFullScreen:!self.player.isFullScreen animated:YES];

                href = [PublicObj decrypt:href];
                paste.string = href;
                [MBProgressHUD showSuccess:YZMsg(@"复制成功")];
            }

        }else if (codeEvent == 9){
            if (![minstr([infoDic valueForKey:@"limit_status"]) isEqual:@"1"]) {
                [MBProgressHUD showError:YZMsg(@"该视频不能保存")];
                return;
            }
            [self.player enterFullScreen:!self.player.isFullScreen animated:YES];

            _isDownLoading = YES;
            [self downloadVideo:RKDownType_Save];

        }else if (codeEvent == 10){
            if ([[Config getOwnID]intValue]<0) {
                [self.player enterFullScreen:!self.player.isFullScreen animated:YES];

                [PublicObj warnLogin];
                return;
            }
            if (![minstr([infoDic valueForKey:@"video_status"]) isEqual:@"1"]) {
                [MBProgressHUD showError:minstr([infoDic valueForKey:@"video_msg"])];
                return;
            }
            if (![minstr([infoDic valueForKey:@"limit_status"]) isEqual:@"1"]) {
                [MBProgressHUD showError:YZMsg(@"该视频不能合拍")];
                return;
            }
            [self.player enterFullScreen:!self.player.isFullScreen animated:YES];

            _isDownLoading = YES;
            [self downloadVideo:RKDownType_Chorus];

        }
    };
    _landShareView.shareHideEvent = ^{
        [weakSelf.landShareView removeFromSuperview];
        weakSelf.landShareView = nil;
    };
    [self addSubview:_landShareView];
}
-(void)clickVideoCollectionAni:(BOOL)animation {
    NSString *videoID = minstr([self.playDoc valueForKey:@"id"]);
    YBWeakSelf;
    [WYNetworking postWithUrl:@"video.addCollection" Dic:@{@"videoid":videoID} Suc:^(int code, id info, NSString *msg) {
        if (code == 0) {
            NSDictionary *infoDic = [info firstObject];
            NSString *iscollection = minstr([infoDic valueForKey:@"iscollection"]);
            NSString *collections  = minstr([infoDic valueForKey:@"collections"]);
            NSDictionary *newDic = @{@"iscollection":iscollection,@"collections":collections};
//            [weakSelf updateDataDic:newDic];
//            if (weakSelf.videoCellEvent) {
//                weakSelf.videoCellEvent(@"视频-收藏", newDic);
//            }
//            [_collectionBtn setTitle:collections forState:0];
//            _collectionBtn = [PublicObj setUpImgDownText:_collectionBtn];
//            _collectionBtn.selected = [iscollection intValue];
            if (animation) {
                [weakSelf colAnimationWithIsCol:iscollection];
            }else{
                [MBProgressHUD showError:msg];
            }
        }else{
            [MBProgressHUD showError:msg];
        }
    } Fail:^(id fail) {
        
    }];
}
//收藏-取消收藏动画
-(void)colAnimationWithIsCol:(NSString *)isCol {
    NSMutableArray *m_sel_arr = [NSMutableArray array];
    NSString *endImgName = @"";
    UIControlState btnState;
    if ([isCol isEqual:@"1"]) {
        for (int i=1; i<=12; i++) {
            UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:@"icon_video_col_%02d",i]];
            [m_sel_arr addObject:img];
        }
        btnState = UIControlStateSelected;
        endImgName = @"icon_video_col_12";
    }else{
        for (int i=1; i<=6; i++) {
            UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:@"icon_video_col_cancel_%02d",i]];
            [m_sel_arr addObject:img];
        }
        btnState = UIControlStateNormal;
        endImgName = @"icon_video_col_01";
    }
}
-(void)clickCommentBtn {
    if ([[Config getOwnID] intValue] <= 0) {
        [self.player enterFullScreen:!self.player.isFullScreen animated:YES];
        [PublicObj warnLogin];
        return;
    }

    NSLog(@"comment:%@",_playDoc);
    NSDictionary *userDic = [_playDoc valueForKey:@"userinfo"];
    NSString *videoUserID = minstr([userDic valueForKey:@"id"]);
    NSString *videoID = minstr([_playDoc valueForKey:@"id"]);
    NSString *commentStr = minstr([_playDoc valueForKey:@"comments"]);
    
    CGFloat min_view_w = self.bounds.size.width;
    CGFloat min_view_h = self.bounds.size.height;
    YBWeakSelf;
    _commentView = [[commentview alloc]initWithFrame:CGRectMake(min_view_w-min_view_w *0.4,0, min_view_w *0.4, _window_width) hide:^(NSString *type) {
    } andvideoid:videoID andhostid:videoUserID count:[commentStr intValue] talkCount:^(id type) {
//        [weakSelf updateCommentNums:type];
    } detail:^(id type) {
        
    } youke:^(id type) {
//        [weakSelf comNeedLogin];
    } andFrom:@""];
    [_commentView resetFream];
    _commentView.closeEvent = ^{
        [weakSelf.commentView removeFromSuperview];
        weakSelf.commentView = nil;
    };
    [self addSubview:_commentView];
}

//下载视频到本地
-(void)downloadVideo:(RKDownType)downType{
//    [self dismiss];
    NSString *href = [NSString stringWithFormat:@"%@",[self.playDoc valueForKey:@"href_w"]];
    if (downType == RKDownType_Chorus) {
        href = [NSString stringWithFormat:@"%@",[self.playDoc valueForKey:@"href"]];
    }
    href = [PublicObj decrypt:href];
    if (href.length <= 0 || [href containsString:@".m3u8"]) {
        if (downType == RKDownType_Save) {
            [MBProgressHUD showError:YZMsg(@"该视频暂不支持下载")];
        }else {
            [MBProgressHUD showError:YZMsg(@"该视频暂不支持合拍")];
        }
        _isDownLoading = NO;
//        [self dismiss];
        return;
    }
    NSString *title = [NSString stringWithFormat:@"%@",[self.playDoc valueForKey:@"title"]];
    if (title.length == 0) {
        NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval a=[dat timeIntervalSince1970]*1000;
        NSString *timeString = [NSString stringWithFormat:@"%d", (int)a];
        title = timeString;
    }
    hud = [MBProgressHUD showHUDAddedTo:[YBBaseAppDelegate sharedAppDelegate].topViewController.view animated:YES];
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    NSString *showDesText = YZMsg(@"正在下载视频");
    downType == RKDownType_Save ? (showDesText = YZMsg(@"正在下载视频")):(showDesText = YZMsg(@"请稍等..."));
    hud.label.text = showDesText;
    //1.创建会话管理者
    //AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
    NSURL *url = [NSURL URLWithString:href];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSMutableURLRequest *m_reques = [request mutableCopy];
    [m_reques addValue:h5url forHTTPHeaderField:@"referer"];
    request = [m_reques copy];
    NSURLSessionDownloadTask *download = [[WYNetworking ybnetManager] downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        //hud.progress = downloadProgress.fractionCompleted;
        dispatch_async(dispatch_get_main_queue(), ^{
            hud.progress = downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
        });
        //监听下载进度
        //completedUnitCount 已经下载的数据大小
        //totalUnitCount     文件数据的中大小
        NSLog(@"%f",1.0 *downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
        NSLog(@"targetPath:%@",targetPath);
        NSLog(@"fullPath:%@",fullPath);
        
        return [NSURL fileURLWithPath:fullPath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        fullPathsss = filePath;
        NSLog(@"%@",filePath);
        
        if (downType == RKDownType_Save) {
            UISaveVideoAtPathToSavedPhotosAlbum([filePath path], self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                _isDownLoading = NO;
//                [self dismiss];
                [MBProgressHUD hideHUDForView:[YBBaseAppDelegate sharedAppDelegate].topViewController.view animated:YES];
                if ([PublicObj checkNull:[fullPathsss path]]) {
                    [MBProgressHUD showPop:YZMsg(@"该视频暂不支持合拍")];
                    return ;
                }
//                if (self.shareEvent) {
//                    self.shareEvent(4, [fullPathsss path]);
//                }
                if (self.player.totalTime < 5) {
                    [MBProgressHUD showPop:YZMsg(@"该视频时长太短,无法合拍")];
                    [[NSFileManager defaultManager] removeItemAtPath:[fullPathsss path] error:nil];
                    return;
                }
                if ([YBYoungManager shareInstance].youngSwitch == 1) {
                    [MBProgressHUD showError:YZMsg(@"青少年模式下不支持该功能")];
                    return;
                }
                TCVideoRecordViewController *recorddVC = [[TCVideoRecordViewController alloc]init];
                recorddVC.mp4Path = [fullPathsss path];
                recorddVC.recordType = RecordType_Chorus;
                [[YBBaseAppDelegate sharedAppDelegate]pushViewController:recorddVC animated:YES];

            });
        }
        
    }];
    
    //3.执行Task
    [download resume];
    
}
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo: (void *)contextInfo {
    if (error == nil) {
        NSLog(@"视频保存成功");
        hud.label.text = YZMsg(@"视频保存成功");
    }else{
        NSLog(@"视频保存失败");
        hud.label.text = YZMsg(@"频保存失败");
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUDForView:[YBBaseAppDelegate sharedAppDelegate].topViewController.view animated:YES];
        _isDownLoading = NO;
//        [self dismiss];
    });
    BOOL isOk = [[NSFileManager defaultManager] removeItemAtPath:[fullPathsss path] error:nil];
    NSLog(@"%d",isOk);
}

@end
